package com.sinsz.wxpn.open.message.impl;

import com.fcibook.quick.http.QuickHttp;
import com.fcibook.quick.http.ResponseBody;
import com.sinsz.common.exception.ApiException;
import com.sinsz.wxpn.open.BaseWxpn;
import com.sinsz.wxpn.open.message.TemplateMessageService;
import com.sinsz.wxpn.open.message.support.TemplateData;
import com.sinsz.wxpn.open.support.FormaterUtils;
import com.sinsz.wxpn.properties.WxpnProperties;
import com.sinsz.wxpn.support.Constant;
import org.nutz.http.Header;
import org.nutz.http.Http;
import org.nutz.http.Response;
import org.nutz.json.Json;
import org.nutz.json.JsonFormat;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 模板消息接口实现
 * @author chenjianbo
 * @date 2018-11-14
 */
public class TemplateMessageServiceImpl extends BaseWxpn implements TemplateMessageService {

    public TemplateMessageServiceImpl(WxpnProperties prop) {
        super(prop);
    }

    @Override
    public String fetchTemplateId(String token, String shortId) {
        if (StringUtils.isEmpty(token)) {
            throw new ApiException(Constant.DEFAULT_ERRORCODE, "用户授权Token不能为空");
        }
        if (StringUtils.isEmpty(shortId)) {
            throw new ApiException(Constant.DEFAULT_ERRORCODE, "模板库模板编号不能为空");
        }
        Map<String, String> map = new HashMap<>(0);
        map.put("template_id_short", shortId);
        try {
            Response response = Http.post3(Constant.API_ADD_TEMPLATE + token, Json.toJson(map, JsonFormat.tidy()), Header.create().set("Content-Type", "application/json"), Constant.TIME_OUT, Constant.TIME_OUT);
            if (response.isOK()) {
                return FormaterUtils.defaultFormat(response.getContent("UTF-8"));
            } else {
                throw new ApiException(Constant.DEFAULT_ERRORCODE, Json.toJson(response, JsonFormat.tidy()));
            }
        } catch (Exception e) {
            e.printStackTrace(System.out);
            throw new ApiException(Constant.DEFAULT_ERRORCODE, "接口请求异常.");
        }
    }

    @Override
    public String fetchAllTemplate(String token) {
        if (StringUtils.isEmpty(token)) {
            throw new ApiException(Constant.DEFAULT_ERRORCODE, "用户授权Token不能为空");
        }
        Map<String, String> map = new HashMap<>(0);
        map.put("access_token", token);
        try {
            ResponseBody response = new QuickHttp().addParames(map).url(Constant.GET_ALL_PRIVATE_TEMPLATE).get().setConnectionTimeout(Constant.TIME_OUT).body();
            return FormaterUtils.defaultFormat(response.text());
        } catch (Exception e) {
            e.printStackTrace(System.out);
            throw new ApiException(Constant.DEFAULT_ERRORCODE, "接口请求异常.");
        }
    }

    @Override
    public String delTemplateById(String token, String templateId) {
        if (StringUtils.isEmpty(token)) {
            throw new ApiException(Constant.DEFAULT_ERRORCODE, "用户授权Token不能为空");
        }
        if (StringUtils.isEmpty(templateId)) {
            throw new ApiException(Constant.DEFAULT_ERRORCODE, "我的模板中对应模板ID不能为空");
        }
        Map<String, String> map = new HashMap<>(0);
        map.put("template_id", templateId);
        try {
            Response response = Http.post3(Constant.DEL_PRIVATE_TEMPLATE + token, Json.toJson(map, JsonFormat.tidy()), Header.create().set("Content-Type", "application/json"), Constant.TIME_OUT, Constant.TIME_OUT);
            if (response.isOK()) {
                return FormaterUtils.defaultFormat(response.getContent("UTF-8"));
            } else {
                throw new ApiException(Constant.DEFAULT_ERRORCODE, Json.toJson(response, JsonFormat.tidy()));
            }
        } catch (Exception e) {
            e.printStackTrace(System.out);
            throw new ApiException(Constant.DEFAULT_ERRORCODE, "接口请求异常.");
        }
    }

    @Override
    public String sendTemplateMessage(String token, String toUserOpenid, String templateId, String url,
                                            String miniProgramAppid, String miniProgramPagePath, List<TemplateData> data) {
        if (StringUtils.isEmpty(token)) {
            throw new ApiException(Constant.DEFAULT_ERRORCODE, "用户授权Token不能为空");
        }
        if (StringUtils.isEmpty(toUserOpenid)) {
            throw new ApiException(Constant.DEFAULT_ERRORCODE, "接收人Openid不能为空");
        }
        if (StringUtils.isEmpty(templateId)) {
            throw new ApiException(Constant.DEFAULT_ERRORCODE, "消息模板ID不能为空");
        }
        if (data == null) {
            throw new ApiException(Constant.DEFAULT_ERRORCODE, "模板参数不合法");
        }
        List<TemplateData> datas = data.stream().filter(Objects::nonNull).collect(Collectors.toList());
        if (datas.isEmpty() || datas.size() < 4) {
            throw new ApiException(Constant.DEFAULT_ERRORCODE, "模板参数不合法");
        }
        //Body请求参数组装
        Map<String, Object> map = new HashMap<>(0);
        map.put("touser", toUserOpenid);
        map.put("template_id", templateId);
        if (!StringUtils.isEmpty(url)) {
            map.put("url", url);
        }
        if (!StringUtils.isEmpty(miniProgramAppid)) {
            Map<String, String> mini = new HashMap<>(0);
            mini.put("appid", miniProgramAppid);
            if (!StringUtils.isEmpty(miniProgramPagePath)) {
                mini.put("pagepath", miniProgramPagePath);
            }
            map.put("miniprogram", mini);
        }
        Map<String, Object> mData = new HashMap<>(0);
        for (int i = 0; i < datas.size(); i++) {
            TemplateData templateData = datas.get(i);
            Map<String, String> temp = new HashMap<>(0);
            temp.put("value", StringUtils.isEmpty(templateData.getValue())?"***":templateData.getValue());
            if (!StringUtils.isEmpty(templateData.getColor())) {
                temp.put("color", templateData.getColor());
            }
            if (i == 0) {
                mData.put("first", temp);
            } else if (i == datas.size() -1){
                mData.put("remark", temp);
            } else {
                mData.put("keyword" + i, temp);
            }
        }
        if (!mData.isEmpty()) {
            map.put("data", mData);
        }
        try {
            Response response = Http.post3(Constant.TEMPLATE_MESSAGE_SEND + token, Json.toJson(map, JsonFormat.tidy()), Header.create().set("Content-Type", "application/json"), Constant.TIME_OUT, Constant.TIME_OUT);
            if (response.isOK()) {
                return FormaterUtils.defaultFormat(response.getContent("UTF-8"));
            } else {
                throw new ApiException(Constant.DEFAULT_ERRORCODE, Json.toJson(response, JsonFormat.tidy()));
            }
        } catch (Exception e) {
            e.printStackTrace(System.out);
            throw new ApiException(Constant.DEFAULT_ERRORCODE, "接口请求异常.");
        }
    }

}
